<?php

namespace XWAM\Model;

/**
 * 角色数据库模型
 *
 * @since 1.0.0 <2015-3-25> SoChishun <14507247@qq.com> Added.
 */
class RoleModel extends AppbaseModel {

    /**
     * 数据表名称
     * @var string
     */
    protected $tableName = 't_porg_auth_group';

    /**
     * 是否批量验证
     * @var boolean
     */

    /**
     * 获取id_text列表
     * @param boolean $keyIsId 键名是否是ID(默认false)
     * @return type
     * @since 1.0 2016-6-1 SoChishun Added.
     * @since 1.1 2017-3-16 SoChishun get_idtext_list()重命名为getIdTextList()
     */
    function getIdTextList($keyIsId = false) {
        $list = array();
        if ($keyIsId) {
            $list = $this->where(array('status' => 1))->cache('group_idtext_kvlist', 10)->order('sort, id')->getField('id, title as text');
        } else {
            $list = $this->where(array('status' => 1))->cache('group_idtext_list', 10)->order('sort, id')->field('id,title as text')->select();
        }
        return $list;
    }

    /**
     * 保存角色
     * @return true|string|array
     * @since 1.0 2015-3-6 by sutroon
     */
    public function saveRole() {
        $rules = array(
            array('title', 'require', '角色标题必须填写!'),
            array('status', 'number', '状态有误!'),
            array('site_id', 'number', 'SiteID无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$this->validate($rules)->create()) {
            $this->returnMsg(false, $this->getError());
        }
        // 显示名称不填则默认与角色名称一致
        if (empty($this->display_title)) {
            $this->display_title = $this->title;
        }
        if (empty($this->id)) {
            unset($this->data['id']);
            $result = $this->add();
        } else {
            $result = $this->save();
        }
        return $this->returnMsg($result);
    }

    /**
     * 复制角色
     * @return type
     * @since 1.0 <2015-10-28> SoChishun Added.
     */
    function copyRole($id) {
        $table = $this->tableName;
        $this->execute("insert into $table (title,`code`,rules,site_id) select concat(title,'_new'),`code`,rules,site_id from $table where id=$id");
        return $this->returnMsg(true);
    }

    public function saveRule($role_id, $rules) {
        $result = $this->where(array('id' => $role_id))->setField('rules', implode(',', $rules));
        return $this->returnMsg($result);
    }

    public function deleteRole($id = '') {
        if (!$id) {
            return $this->returnMsg(false, '参数无效');
        }
        $table = $this->tableName;
        $list = $this->query('select a.title from ' . $table . ' a inner join ' . $table . ' b on b.pid=a.id where b.pid in (' . $id . ')');
        $names = false;
        if ($list) {
            foreach ($list as $row) {
                $names .= ',' . $row['title'];
            }
        }
        if ($names) {
            return $this->returnMsg(false, '以下项目有子项目,请先转移子项目:' . "\n" . ltrim($names, ','));
        }
        // 判断是否有引用
        $user_role_id = $this->table('t_porg_user')->where(array('role_id' => $id))->getField('role_id', true);
        if ($user_role_id) {
            $names = $this->where(array('id' => array('in', $user_role_id)))->getField('title', true);
            return $this->returnMsg(false, '以下项目正在被用户使用,无法删除:' . "\n" . implode(',', $names));
        }
        $result = $this->delete($id);
        return $this->returnMsg($result);
    }

    function changeStatus($id, $status) {
        $result = $this->where(array('id' => $id))->setField(array('status' => $status));
        return $this->returnMsg($result);
    }

    function changeSort($id, $sort) {
        $result = $this->where(array('id' => $id))->setField(array('sort' => $sort));
        return $this->returnMsg($result);
    }

    /**
     * 批量更新外键对应的标题
     * @param type $all
     * @since 1.0 2017-3-17 SoChishun Added.
     */
    static function updateForeignTitle($all = false, $id = '') {
        M()->execute("update t_porg_user u left join t_porg_auth_group r on u.role_id=r.id set u.role_title=r.title where " . ($id ? "u.role_id in ($id)" : "u.role_id > 0") . ($all || $id ? '' : " and u.role_title=''"));
    }

}
